/**
 * 数据字典列表
 */
(function (app, ng) {
    'use strict';
    /**
     * 注册控制器
     */
    app.controller('DictListCtrl', DictListCtrl);

    /**
     * 依赖项
     * @type {[string,string,string,string,string,string,string,string]}
     */
    DictListCtrl.$inject = ['$scope', '$http', 'dialogs', '$state', 'DynamicI18n', 'DictService', 'Constant', '$timeout']

    /**
     * 声明控制器
     * @param $scope
     * @param $http
     * @param dialogs
     * @param $state
     * @param DynamicI18n
     * @param DictService
     * @param Constant
     * @param $timeout
     * @constructor
     */
    function DictListCtrl($scope, $http, dialogs, $state, DynamicI18n, DictService, Constant, $timeout) {
        var vm = this;
        // var vm = $scope.vm = this;
        var defaultQuery = {};
        vm.query = angular.copy(defaultQuery);

        vm.flexigridObjDModel = {};
        vm.options = DictService.getGirdOptions();

        vm.treeObj = {};
        vm.treeSetting = {
            async: {
                url: ISS.getPath('/dictionary/tree'),
                enable: true,
                dataType: "json",
                autoParam: ["id", "category"],
                otherParam: {"lang": ISS.lang}
            },
            data: {
                simpleData: {
                    enable: true
                }
            },
            edit: {
                enable: false,
                removeTitle: "删除节点名称",
                renameTitle: "编辑节点名称",
                showRemoveBtn: true,
                showRenameBtn: true
            },
            callback: {
                onAsyncSuccess: function (event, treeId, treeNode, msg) {
                    if (!treeNode) {
                        $timeout(function () {
                            $("#dictTree_2_span").click();
                        }, 200);
                    }
                },
                onClick: function (event, treeId, treeNode, clickFlag) {
                    setParam(treeNode);
                },
                onRemove: function (event, treeId, treeNode, clickFlag) {

                    zTreeOnRemove(treeNode);
                },
                onRename: function (event, treeId, treeNode, isCancel) {

                    zTreeOnRename(treeNode);
                }
            }
        };
        var zTreeOnRemove = function (data) {

            vm.selectedId = data.id;
            vm.selectedName = data.name;
            if (ISS.isNotEmpty(data.id)) {
                // 弹出确认删除提示信息
                var dlg = dialogs.confirm(undefined, getMessage("common.deleteConfirm"));
                dlg.result.then(function (param) {
                    DictService.deleteDictCategory(data.id).then(function (data) {
                        // 刷新列表
                        vm.flexigridObjDModel.flexReload();
                        // 刷新左侧树
                        reAsyncChildNodes();
                        //弹出提示信息
                        dialogs.notify(data.msg);
                    });
                });
            } else {
                // 提示请选择一条或多条信息
                dialogs.notify(undefined, getMessage("common.plzSelectOneRecourd"));
            }

        };

        var zTreeOnRename = function (data) {
            vm.selectedId = data.id;
            vm.selectedName = data.name;
            if (ISS.isNotEmpty(data.id)) {
                // 弹出确认删除提示信息
                var dlg = dialogs.confirm(undefined, getMessage("common.updateConfirm"));
                dlg.result.then(function (param) {
                    DictService.updateDictCategory(data.id, data.name).then(function (data) {
                        // 刷新列表
                        vm.flexigridObjDModel.flexReload();
                        // 刷新左侧树
                        reAsyncChildNodes();
                        //弹出提示信息
                        dialogs.notify(data.msg);
                    });
                });
            } else {
                // 提示请选择一条或多条信息
                dialogs.notify(undefined, getMessage("common.plzSelectOneRecourd"));
            }
        };

        // 重新异步加载子节点，新增或修改的时候
        var reAsyncChildNodes = function () {
            var parentNode = vm.selectNode.isParent ? vm.selectNode : vm.selectNode.getParentNode();
            /*var selectedNodes = vm.treeObj.getSelectedNodes();
            if (selectedNodes.length != 0) {
                parentNode = selectedNodes[0];
                vm.treeObj.selectNode(parentNode);
                // 设置为父节点，不然不加载
                parentNode.isParent = true;
            }*/
            vm.treeObj.reAsyncChildNodes(null, "refresh");
        };

        //获取数据字典类型
        DictService.getCategories(ISS.lang).then(function (data) {
            vm.categories = data;
            //if (vm.dict && !vm.dict.category && data && data[0]) vm.dict.category = data[0].code; // 默认值
        });

        // 设置查询参数
        var setParam = function (data) {
            vm.selectNode = data;
            // 点击建筑树节点时，查询该建筑节点下一级的建筑（不包括该节点）
            vm.flexigridObjDModel.flexOptions({
                newp: 1,
                extParam: {
                    'lang': ISS.lang,
                    'category': data.attrMap.category
                }
            }).flexReload();
        };
        //查询
        vm.search = function () {
            var param = {};
            param = angular.copy(vm.query);
            // 语言
            param.lang = ISS.lang;
            // 获取ztree中的参数
            var nodes = vm.treeObj.getSelectedNodes();
            if (nodes.length > 0)
                param.category = nodes[0].attrMap.category;
            vm.flexigridObjDModel.flexOptions({
                newp: 1,
                extParam: param
            }).flexReload();
        };

        // 重置
        vm.reset = function () {
            vm.query = angular.copy(defaultQuery);
            vm.search();
        };

        // 新增
        vm.addDict = function () {
            vm.dict = {};
            vm.categories.forEach(function (item, index) {
                if (item.code == vm.selectNode.attrMap.category) {
                    vm.dict.category = item;
                }
            });
            createEditDialog({isAdd: true});
        };
        // 删除
        vm.delDict = function (id) {
            if (ISS.isNotEmpty(id)) {
                // 弹出确认删除提示信息
                var dlg = dialogs.confirm(undefined, getMessage("common.deleteConfirm"));
                dlg.result.then(function (param) {
                    DictService.deleteDict(id).then(function (data) {
                        // 刷新列表
                        vm.flexigridObjDModel.flexReload();
                        // 刷新左侧树
                        //reAsyncChildNodes();
                        //弹出提示信息
                        dialogs.notify(data.msg);
                    });
                });
            } else {
                // 提示请选择一条或多条信息
                dialogs.notify(undefined, getMessage("common.plzSelectOneRecourd"));
            }
        }
        // 更新数据字典JS文件
        vm.updateJs = function () {
            DictService.updateDictJs().then();
        };
        // 修改
        vm.updateDict = function (datadictCode) {
            DictService.getDict(datadictCode).then(function (data) {
                vm.categories.forEach(function (item, index) {
                    if (item.code == data.category) {
                        data.category = item;
                    }
                });
                createEditDialog({
                    isAdd: false,
                    dict: data
                });
            });
        };

        /**
         * 编辑模态框
         * @param data
         * @returns {app/modules/dict/dict-edit.html}
         */
        function createEditDialog(data) {
            data = data || {};
            var dialog = dialogs.create('app/modules/dict/dict-edit.html', 'DictEditCtrl', data, {
                size: 'lg',
                keyboard: true,
                backdrop: false
            });
            dialog.result.then(function () {
                // 刷新列表
                vm.flexigridObjDModel.flexReload();
            });
            return dialog;
        }
    }
})(iApp.module(), window.angular);

/**
 * 编辑数据字典
 */
(function (app, ng) {
    'use strict';
    /**
     * 注册控制器
     */
    app.controller('DictEditCtrl', DictEditCtrl);

    /**
     * 依赖项
     * @type {[string,string,string,string,string,string,string,string]}
     */
    DictEditCtrl.$inject = ['$scope', '$state', 'dialogs', '$uibModalInstance', 'DynamicI18n', 'DictService', 'Constant', 'data'];

    /**
     * 声明控制器
     * @param $scope
     * @param $state
     * @param dialogs
     * @param $uibModalInstance
     * @param DynamicI18n
     * @param DictService
     * @param Constant
     * @param data
     * @constructor
     */
    function DictEditCtrl($scope, $state, dialogs, $uibModalInstance, DynamicI18n, DictService, Constant, data) {
        /* Init Start */
        var vm = $scope.vm = this;
        vm.dict = data.dict || {}; // 初始化当前字典
        vm.categoryDictionary = vm.dict.category;
        $scope.dialog = $uibModalInstance;
        var isAdd = vm.isAdd = data.isAdd;
        var isUpdate = vm.isUpdate = !isAdd;
        // 初始化数据字典
        initCategories();

        if (isAdd) { // 新增
            vm.title = "common.add";
        } else { // 更新
            vm.title = "common.edit";
        }
        // 提交数据
        vm.save = save;

        /* Method */
        /**
         * 初始化数据字典
         */
        function initCategories() {
            // 获取数据字典类型
            DictService.getCategories(ISS.lang).then(function (data) {
                vm.categories = data;
                if (!vm.dict.category && data && data[0]) vm.dict.category = data[0].code; // 默认值
            });
        }

        /**
         * 新增/修改请求
         * @returns {promise}
         */
        function editPromise(dict, i18n) {
            if (isAdd)
                return DictService.addDict(dict, i18n);
            return DictService.update(dict, i18n);
        }

        /**
         * 新增/修改
         */
        function save() {
            // 新增/修改时，页面绑定的是content
            vm.dict.desc = vm.dict.content;
            vm.dict.category = vm.categoryDictionary.code;

            // 国际化类型 = 是否添加数据字典类型 ? 字典类型 : 字典
            var type = vm.dict.category == Constant.DICT.CATEGORY ? Constant.I18N.TYPE.CATEGORY : Constant.I18N.TYPE.DICTIONARY;
            var i18n = {
                languageId: DynamicI18n.currentLangId(),
                objectId: vm.dict.id,
                type: type,
                name: vm.dict.content || vm.dict.desc
            };
            editPromise(vm.dict, i18n).then(function (data) {
                if (data.success === false) { // 失败
                    dialogs.notify(data);
                } else { // 成功
                    dialogs.notify(data).closed.then(function () {
                        $uibModalInstance.close();
                    });
                }
            });
        }
    }
})(iApp.module(), window.angular);